<template>
  <div class="products-container">
    <el-card shadow="hover">
      <template #header>
        <div class="card-header">
          <span class="title">助农商品</span>
          <el-button type="primary" @click="showAddDialog">新增商品</el-button>
        </div>
      </template>

      <el-table :data="productsList" border style="width: 100%" v-loading="loading">
        <el-table-column prop="name" label="商品名称" width="100" />
        <el-table-column prop="description" label="商品描述" width="100" :show-overflow-tooltip="true" />
        <el-table-column prop="price" label="价格" width="100" />
        <el-table-column prop="stock" label="库存" width="100" />
        <el-table-column prop="sales" label="销量" width="100" />

        <!-- AgriculturalProducts.vue -->
        <el-table-column label="助农状态">
          <template #default="{ row }">
            <el-switch
                v-model="row.isAgriculture"
                active-value="1"
                inactive-value="0"
                active-text="是"
                inactive-text="否"
                @change="handleAgricultureStatusChange(row.id, row.isAgriculture)"/>
          </template>
        </el-table-column>

        <!-- 修改后的"状态"列 -->
        <el-table-column label="状态" width="120">
          <template #default="{ row }">
            <el-switch
                v-model="row.status"
                :active-value="1"
                :inactive-value="0"
                active-text="上架"
                inactive-text="下架"
                @change="handleStatusChange(row.id, row.status)"
            />
          </template>
        </el-table-column>

        <el-table-column label="操作" width="150">
          <template #default="{ row }">
            <el-button
                size="small"
                type="primary"
                @click="handleEdit(row)"
            >编辑</el-button>
            <el-button
                size="small"
                type="danger"
                @click="handleDelete(row.id)"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <el-dialog v-model="dialogVisible" :title="productForm.id ? '编辑助农商品' : '新增助农商品'" width="60%">
        <el-form :model="productForm" :rules="rules" ref="productFormRef" label-width="100px">
          <el-form-item label="商品名称" prop="name">
            <el-input v-model="productForm.name" placeholder="请输入商品名称" clearable />
          </el-form-item>
          <el-form-item label="商品描述" prop="description">
            <el-input
                v-model="productForm.description"
                type="textarea"
                placeholder="请输入商品描述"
                clearable
                :rows="5"
            />
          </el-form-item>
          <el-form-item label="产品 ID" prop="productId">
            <el-input v-model="productForm.productId" placeholder="请输入产品 ID" clearable />
          </el-form-item>

          <el-form-item label="价格" prop="price">
            <el-input-number v-model="productForm.price" :min="0" :precision="2" />
          </el-form-item>
          <el-form-item label="库存" prop="stock">
            <el-input-number v-model="productForm.stock" :min="0" />
          </el-form-item>
          <el-form-item label="销量" prop="sales">
            <el-input-number v-model="productForm.sales" :min="0" />
          </el-form-item>
          <el-form-item label="状态" prop="status">
            <el-switch
                v-model="productForm.status"
                :active-value="1"
                :inactive-value="0"
                active-text="上架"
                inactive-text="下架"
            />
          </el-form-item>
          <el-form-item label="助农状态" prop="isAgriculture">
            <el-switch
                v-model="productForm.isAgriculture"
                active-text="是"
                inactive-text="否"
            />
          </el-form-item>
          <el-form-item label="主图上传">
            <el-upload
                class="avatar-uploader"
                :show-file-list="false"
                :before-upload="beforeImageUpload"
                :http-request="customImageUpload"
            >
              <div class="avatar-wrapper">
                <img
                    v-if="productForm.imageUrl"
                    :src="productForm.imageUrl"
                    class="avatar-image"
                />
                <div v-else class="avatar-placeholder">
                  <el-icon class="upload-icon"><Plus /></el-icon>
                  <span class="upload-text">上传主图</span>
                </div>
                <div class="upload-mask">
                  <el-icon class="upload-icon"><Edit /></el-icon>
                  <span class="upload-text">更换图片</span>
                </div>
              </div>
              <div class="mt-2 text-sm text-gray-500">建议尺寸：800x800像素，格式：JPG/PNG</div>
            </el-upload>
          </el-form-item>
          <el-form-item label="详情图链接" prop="detailUrl">
            <el-input v-model="productForm.detailUrl" placeholder="请输入详情图链接" clearable />
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="dialogVisible = false">取消</el-button>
            <el-button type="primary" @click="submitForm">保存</el-button>
          </span>
        </template>
      </el-dialog>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import axios from 'axios'
import { ElMessage } from 'element-plus'
import { Plus, Edit } from '@element-plus/icons-vue'

// 从localStorage获取用户信息
const userStr = localStorage.getItem('admin')
const user = userStr ? JSON.parse(userStr) : null

const productsList = ref([])
const loading = ref(false)
const dialogVisible = ref(false)
const productForm = ref({
  id: null,
  productId: '',
  name: '',
  description: '',
  price: 0,
  stock: 0,
  sales: 0,
  status: 1,
  isAgriculture: true,
  imageUrl: '',
  detailUrl: '',
})
const rules = {
  name: [
    { required: true, message: '商品名称不能为空', trigger: 'blur' },
    { min: 2, max: 100, message: '长度在2到100个字符', trigger: 'blur' }
  ],
  productId: [
    { required: true, message: '产品 ID 不能为空', trigger: 'blur' }
  ],
  description: [
    { required: true, message: '商品描述不能为空', trigger: 'blur' }
  ],
  price: [
    { type: 'number', min: 0, message: '价格必须大于等于0', trigger: 'blur' }
  ],
  stock: [
    { type: 'number', min: 0, message: '库存必须大于等于0', trigger: 'blur' }
  ],
  sales: [
    { type: 'number', min: 0, message: '销量必须大于等于0', trigger: 'blur' }
  ],
  imageUrl: [
    { required: true, message: '主图不能为空', trigger: 'blur' }
  ],
  detailUrl: [
    { required: true, message: '详情图链接不能为空', trigger: 'blur' }
  ],
}
const productFormRef = ref(null)

const fetchProducts = async () => {
  try {
    loading.value = true
    const response = await axios.get(`${BASE_URL}/api/v1/government/list`)
    productsList.value = response.data.data.map(item => ({
      id: item.id,
      productId: item.merchantId,
      name: item.name || '',
      description: item.description || '',
      price: item.price || 0,
      stock: item.stock || 0,
      sales: item.sales || 0,
      status: item.status || 1,
      isAgriculture: item.isAgriculture || true,
      imageUrl: item.imageUrl || '',
      detailUrl: item.detailUrl || ''
    }))
  } catch (error) {
    console.error('获取助农商品失败:', error)
    ElMessage.error('获取助农商品失败')
  } finally {
    loading.value = false
  }
}

const showAddDialog = () => {
  productForm.value = {
    id: null,
    productId: '',
    name: '',
    description: '',
    price: 0,
    stock: 0,
    sales: 0,
    status: 1,
    isAgriculture: true,
    imageUrl: '',
    detailUrl: '',
  }
  dialogVisible.value = true
}

const handleEdit = (rowData) => {
  productForm.value = { ...rowData }
  dialogVisible.value = true
}

const handleDelete = async (id) => {
  try {
    await ElMessageBox.confirm('确定要删除这条商品吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })

    await axios.post(`${BASE_URL}/api/v1/government/private/deleteProduct`, {
      id: id
    })

    ElMessage.success('删除成功')
    fetchProducts()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error)
      ElMessage.error('删除失败')
    }
  }
}

const handleAgricultureStatusChange = async (id, status) => {
  try {
    await axios.post(`${BASE_URL}/api/v1/government/private/updateAgricultureStatus`, {
      id: id,
      isAgriculture: status
    })
    ElMessage.success('助农状态更新成功')
  } catch (error) {
    console.error('助农状态更新失败:', error)
    ElMessage.error('助农状态更新失败')
  }
}

const handleStatusChange = async (id, status) => {
  try {
    await axios.post(`${BASE_URL}/api/v1/government/private/updateProductStatus`, {
      id: id,
      status: status
    })
    ElMessage.success('商品状态更新成功')
  } catch (error) {
    console.error('商品状态更新失败:', error)
    ElMessage.error('商品状态更新失败')
  }
}

// 图片上传相关
const beforeImageUpload = (file) => {
  const isImage = file.type.startsWith('image/')
  const isLt5M = file.size / 1024 / 1024 < 5

  if (!isImage) {
    ElMessage.error('只能上传图片文件!')
    return false
  }
  if (!isLt5M) {
    ElMessage.error('图片大小不能超过5MB!')
    return false
  }

  return true
}

const customImageUpload = async (options) => {
  const { file } = options
  try {
    const formData = new FormData()
    formData.append('file', file)
    formData.append('userId', user?.id || '123')

    const response = await axios.post(`${BASE_URL}/v1/file/upload`, formData, {
      headers: {
        'Content-Type': 'multipart/form-data',
        'Authorization': `Bearer ${user?.token || ''}`
      }
    })

    if (response.data.code === 2000) {
      productForm.value.imageUrl = response.data.data
    } else {
      throw new Error(response.data.message || '上传失败')
    }
  } catch (error) {
    ElMessage.error('图片上传失败: ' + error.message)
    throw error
  }
}

const submitForm = async () => {
  try {
    await productFormRef.value.validate()
    const payload = { ...productForm.value }

    let response
    if (payload.id) {
      response = await axios.post(`${BASE_URL}/api/v1/government/private/reviseProduct`, payload)
    } else {
      response = await axios.post(`${BASE_URL}/api/v1/government/private/addProduct`, payload)
    }

    if (response.data.code === 200) {
      ElMessage.success('保存成功')
      dialogVisible.value = false
      fetchProducts()
    } else {
      ElMessage.error(response.data.message || '保存失败')
    }
  } catch (error) {
    if (error.name !== 'ValidationError') {
      console.error('保存助农商品失败:', error)
      ElMessage.error('保存助农商品失败')
    }
  }
}

onMounted(() => {
  fetchProducts()
})
</script>

<style scoped>
.products-container {
  margin: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.title {
  font-size: 18px;
  font-weight: 600;
  color: var(--el-text-color-primary);
}

.avatar-uploader {
  --el-avatar-size: 178px;
  width: 100%;
}

.avatar-wrapper {
  position: relative;
  width: 100%;
  min-height: 120px;
  border-radius: 6px;
  overflow: hidden;
  border: 1px dashed var(--el-border-color);
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 20px;
  cursor: pointer;
  transition: border-color 0.3s;
}

.avatar-wrapper:hover {
  border-color: var(--el-color-primary);
}

.avatar-image {
  width: 100%;
  height: 100%;
  object-fit: contain;
}

.avatar-placeholder {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 100%;
  color: #8c939d;
  background-color: #f5f7fa;
}

.upload-mask {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  color: white;
  opacity: 0;
  transition: opacity 0.3s;
}

.avatar-wrapper:hover .upload-mask {
  opacity: 1;
}

.upload-icon {
  font-size: 28px;
  margin-bottom: 8px;
  color: #8c939d;
}

.upload-text {
  font-size: 14px;
  color: #8c939d;
}

.mt-2 {
  margin-top: 0.5rem;
}

.text-sm {
  font-size: 0.875rem;
  line-height: 1.25rem;
}

.text-gray-500 {
  color: #6b7280;
}
</style>